package com.chatbot.application.job;

import com.alibaba.fastjson.JSON;
import com.chatbot.domain.chatgpt.service.IOpenAI;
import com.chatbot.domain.zsxq.model.aggregates.UnAnsweredQuestionAggregates;
import com.chatbot.domain.zsxq.model.vo.Topics;
import com.chatbot.domain.zsxq.service.IZsxqApi;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

/**
 * @author Lenovo
 */
@Slf4j
public class ChatbotTask implements Runnable {

    private String groupName;
    private String groupId;
    private String cookie;
    private IZsxqApi zsxqApi;
    private IOpenAI openAI;

    public ChatbotTask(String groupName, String groupId, String cookie, IZsxqApi zsxqApi, IOpenAI openAI) {
        this.groupName = groupName;
        this.groupId = groupId;
        this.cookie = cookie;
        this.zsxqApi = zsxqApi;
        this.openAI = openAI;
    }


    @Override
    //cron:https://cron.qqe2.com/
    public void run() {
        try {
            //防止回答问题太规律被风控抓到
            if (new Random().nextBoolean()) {
                log.info("{} 随机打烊中...", groupName);
                return;
            }

            GregorianCalendar calendar = new GregorianCalendar();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour > 22 || hour < 7) {
                log.info("{} 打烊时间不工作，AI 下班了！", groupName);
                return;
            }


            UnAnsweredQuestionAggregates unAnsweredQuestionsAggregates = zsxqApi.queryUnAnsweredQuestionsTopicId(groupId, cookie);
            log.info("{} 检索结果：{}", groupName, JSON.toJSONString(unAnsweredQuestionsAggregates));

            List<Topics> topics = unAnsweredQuestionsAggregates.getResp_data().getTopics();
            if (null == topics || topics.isEmpty()) {
                log.info("{} 本次检索未查询到待回答问题", groupName);
                return;
            }

            //一次只回答一个问题
            Topics topic = topics.get(0);

            String answer = openAI.doChatGPT(topic.getTalk().getText().trim());

            //回答问题
            boolean status = zsxqApi.answer(groupId, cookie, topic.getTopic_id(), answer, null, null);
            log.info("{} 编号：{} 问题：{} 回答：{} 状态：{}", groupName, topic.getTopic_id(), topic.getTalk().getText(), answer, status);
        } catch (Exception e) {
            log.error("{} 自动回答问题异常", groupName, e);
        }

    }
}
